import { ReactNode, useState, useEffect, lazy, Suspense, FC } from 'react'
import { Space, Button } from 'antd'
import { LoadingOutlined } from '@ant-design/icons'
import style from './index.module.less'

function Empty () {
  return <div />
}

function initModel (loadFn: () => Promise<{ default: ReactNode }>, setModel: (v: Promise<{ default: any }>) => void, setStatus: (v: boolean) => void, setLoaded: (v: boolean) => void) {
  setModel(new Promise((resolve, reject) => {
    loadFn()
      .then((...p) => {
        setStatus(true)
        setLoaded(true)
        resolve(...p)
      })
      .catch(() => {
        setStatus(false)
        setLoaded(true)
        resolve({ default: <Empty /> })
      })
  }))
}

interface Props {
  loadFn: () => Promise<{ default: any }>,
  close?: () => {},
  toFullInfo?: () => {},
  caseDetail?: {},
  props: any
}

function Main ({ loadFn, close, toFullInfo, caseDetail, props }: Props) {
  const [model, setModel] = useState<Promise<{ default: any }>>()
  const [status, setStatus] = useState(false)
  const [loaded, setLoaded] = useState(false)
  const [component, setComponent] = useState<Promise<any>>()
  useEffect(() => {
    initModel(loadFn, setModel, setStatus, setLoaded)
  }, [loadFn])
  useEffect(() => {
    if (model) {
      setComponent(lazy(() => model) as unknown as Promise<ReactNode>)
    }
  }, [model])
  if (!model) {
    return <div />
  }
  if (loaded && !status) {
    return (
      <div className={style['error-box']}>
        <div className={style['error-message']}>
          <Space>
            <span>加载失败</span>
            <Button type='primary' onClick={() => window.location.reload()}>刷新页面</Button>
          </Space>
        </div>
      </div>
    )
  }
  const Model = component as unknown as FC<any>
  if (Model) {
    return (
      <Suspense fallback={(
        <div className={style['loading-box']}>
          <LoadingOutlined />
        </div>
      )}>
        <Model {...props} />
      </Suspense>
    )
  }
  return <div />
}

export default Main
